'use strict';

const { Controller, Utils } = require('ee-core');
const path = require('path');
const { exec, spawn } = require('child_process');
const { sleep, killProcess, openDefaultBrowser } = require('../utils');
let tasks = [];
let desktopTask = [];

class PixelStreamController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  /**
   * 执行命令打开像素流
   * **/
  async openPixelStream() {
    if (tasks.length > 0) return '插件正在运行中';
    let process1 = exec('E:\\project_config\\CCCCBIM-VDCx-12-23\\VDC\\VDC.exe -AudioMixer -PixelStreamingIP=localhost -PixelStreamingPort=8888 -RenderOffScreen');
    await sleep(1000);
    let args = `powershell.exe -noexit -windowstyle hidden -ExecutionPolicy Bypass -File E:\\project_config\\CCCCBIM-VDCx-12-23\\VDC\\Samples\\PixelStreaming\\WebServers\\SignallingWebServer\\platform_scripts\\cmd\\Start_SignallingServer.ps1`;
    let process2 = spawn('powershell', [`powershell -command "Start-Process powershell -ArgumentList '${args}' -Verb RunAs"`]);
    await sleep(1000);
    this.app.service.websocket.start();
    // 添加nodejs工具包,防止用户没有安装nodejs环境,运行不了命令
    // let process3 = exec(`${path.join(Utils.getHomeDir(), './build/extraResources/node-v16.17.0-win-x64/node.exe')} ${path.join(__dirname, './websocket.js')}`);
    let process4 = openDefaultBrowser('http://localhost:8080/vdc');
    await sleep(10 * 1000);
    this.app.service.websocket.wsConnSendText(JSON.stringify({ tag: 'PIXEL_STREAM' })); //开启websocket
    tasks = [process1, process2, process4];
    return '启动中,请稍后';
  }

  // 关闭像素流相关服务
  closePixelStream() {
    if (!tasks.length) return '没有需要关闭的服务';
    tasks.forEach((process) => {
      killProcess(process.pid);
    });
    tasks = [];
    this.app.service.websocket.end(); //关闭websocket
    return '关闭服务操作成功';
  }

  /**
   * @desc 启动引擎桌面端
   */
  startDesktopExe() {
    if (desktopTask.length > 0) {
      return '系统已经启动,请勿重复启动';
    }
    // desktopTask[desktopTask.length] = exec('start E:\\project_config\\CCCCBIM-VDCx-12-23\\Server\\VDC_ClientService.exe');
    desktopTask[desktopTask.length] = exec('start E:\\project_config\\CCCCBIM-VDCx-12-23\\VDC\\VDC.exe');
    return '启动成功';
  }

  /**
   * @desc 关闭引擎桌面端
   */
  endDesktopExe() {
    if (!desktopTask.length) {
      return '没有需要关闭的引擎';
    }
    desktopTask.forEach((desk) => {
      killProcess(desktopTask.pid);
    });
    desktopTask = [];
    return '关闭成功';
  }
}

PixelStreamController.toString = () => ['class PixelStreamController'];
module.exports = PixelStreamController;
``;
